package com.yrd.common.webui;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashSet;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class HttpEngine {
	InetSocketAddress address;
	String servletPackage;
	Server server;
	HashSet<EventSocket> eventSocketSet;
	
	private static HttpEngine httpEngine;
	
	public static HttpEngine getInstance(){
		return httpEngine;
	}
	
	public static HttpEngine create(InetSocketAddress address,String servletPackage){
		if(httpEngine==null){
			httpEngine = new HttpEngine(address,servletPackage);
		}
		return httpEngine;
	}
	public static void distroy() throws Exception{
		httpEngine.stop();
		httpEngine=null;
	}

	private HttpEngine(InetSocketAddress address,String servletPackage) {
		this.address = address;
		this.servletPackage = servletPackage;
	}
	
	public void start() throws Exception{
		server = new Server(address);
		eventSocketSet = new HashSet<EventSocket>();
		ServletContextHandler ctx = new ServletContextHandler(ServletContextHandler.SESSIONS);
		ctx.setContextPath("/");
		ServletHolder holderEvents = new ServletHolder("websocket", EventServlet.class);
		ctx.addServlet(holderEvents, "/websocket/*");
		
		DispatchServlet dispatchServlet = new DispatchServlet(servletPackage);
		ServletHolder holderDispatch = new ServletHolder("dispatch", dispatchServlet);
		ctx.addServlet(holderDispatch, "/request/*");

		DefaultServlet defaultServlet = new DefaultServlet();
		ServletHolder holderPwd = new ServletHolder("default", defaultServlet);
		holderPwd.setInitParameter("resourceBase", "./webui/");
		ctx.addServlet(holderPwd, "/*");
		
		server.setHandler(ctx);
 		server.start();
		System.out.println("HttpEngine 启动");
	}
	public void stop() throws Exception{
		server.stop();
		System.out.println("HttpEngine 关闭");
	}
	
	public synchronized void add(EventSocket eventSocket){
		eventSocketSet.add(eventSocket);
	}
	public synchronized void remove(EventSocket eventSocket){
		eventSocketSet.remove(eventSocket);
	}
	public synchronized void sendMessage(String message){
		for(EventSocket socket : eventSocketSet){
			try {
				socket.getRemote().sendString(message);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public InetSocketAddress getAddress() {
		return address;
	}
	
}
